﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Text.RegularExpressions;


/// <summary>
/// Summary description for DataFlow
/// </summary>
public class DataFlow
{
    
	public DataFlow()
	{
		//
		// TODO: Add constructor logic here
		//  
	}
    public static DataTable csvToDataTable(string file, bool isRowOneHeader)
    {
        string head;
        DataTable csvDataTable = new DataTable();
        //no try/catch - add these in yourselfs or let exception happen
        String[] csvData = File.ReadAllLines(file);

        // Static method:
        Regex re = new Regex("^[-'a-zA-Z]*$");

        // Name does not match schema

        //if no data in file ‘manually’ throw an exception
        if (csvData.Length == 0)
        {
            throw new Exception("CSV File Appears to be Empty");
        }
        String[] headings = csvData[0].Split(',');

        int index = 0; //will be zero or one depending on isRowOneHeader
        if (isRowOneHeader) //if first record lists headers
        {
            index = 1; //so we won’t take headings as data
            //for each heading
            for (int i = 0; i < headings.Length; i++)
            {
                string a = headings[0];

                //replace spaces with underscores for column names
                headings[i] = headings[i].Replace(" ", "_");
                //add a column for each heading
                head = headings[i].ToString();
                csvDataTable.Columns.Add(headings[i], typeof(string));
            }
        }
        else //if no headers just go for col1, col2 etc.
        {
            csvDataTable.Columns.Add("Mobile Number", typeof(string));
            //csvDataTable.Columns.Add("EmailId", typeof(string));
            //csvDataTable.Columns.Add("First Name", typeof(string));
            //csvDataTable.Columns.Add("Last Name", typeof(string));
        }

        //populate the DataTable
        for (int i = index; i < csvData.Length; i++)
        {
            //create new rows
            DataRow row = csvDataTable.NewRow();

            for (int j = 0; j < headings.Length; j++)
            {

                //fill them
                row[j] = csvData[i].Split(',')[j];

            }
            //add rows to over DataTable
            csvDataTable.Rows.Add(row);
        }

        string check_special_characters = CheckString(File.ReadAllText(file));
        if (check_special_characters.Length == 0)
        {
            return csvDataTable;
        }
        else
        {
            csvDataTable = null;
            return csvDataTable;
        }
    }

     public static string CheckString(string text)  
         {
           Regex oRegex = new Regex(@"[<;#$^/>]+", RegexOptions.IgnoreCase);  
           Match oMatch = oRegex.Match(text);  
           oRegex = null;  
         
          if (oMatch.Success)  
             return "Please exclude special characters";  
           else  
             return "";  
         }  
    public void ExportCSV(DataTable data, String filename)
    {
        HttpContext context = HttpContext.Current;
        context.Response.Clear();
        context.Response.ContentType = "text/csv";
        context.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename + ".csv");
        //write column header names
        for (int i = 0; i < data.Columns.Count; i++)
        {
            if (i > 0)
            {
                context.Response.Write(",");
            }
            context.Response.Write(data.Columns[i].ColumnName);

        }
        context.Response.Write(Environment.NewLine);

        foreach (DataRow row in data.Rows)
        {
            for (int i = 0; i < data.Columns.Count; i++)
            {
                if (i > 0)
                {
                    context.Response.Write(",");
                }
                context.Response.Write(row[i].ToString());
            }
            context.Response.Write(Environment.NewLine);
        }
        context.Response.End();

    }
    public void ExportTXT(DataTable data, String filename)
    {
        HttpContext context = HttpContext.Current;
        context.Response.Clear();
        context.Response.ContentType = "text/csv";
        context.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename + ".txt");
        //write column header names
        for (int i = 0; i < data.Columns.Count; i++)
        {
            if (i > 0)
            {
                context.Response.Write(",");
            }
            context.Response.Write(data.Columns[i].ColumnName);

        }
        context.Response.Write(Environment.NewLine);

        foreach (DataRow row in data.Rows)
        {
            for (int i = 0; i < data.Columns.Count; i++)
            {
                if (i > 0)
                {
                    context.Response.Write(",");
                }
                context.Response.Write(row[i].ToString());
            }
            context.Response.Write(Environment.NewLine);
        }
        context.Response.End();

    }
    public static void Export(string fileName, GridView gv)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader(
            "content-disposition", string.Format("attachment; filename={0}", fileName));
        HttpContext.Current.Response.ContentType = "application/ms-excel";

        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                //  Create a form to contain the grid
                Table table = new Table();
                table.GridLines = gv.GridLines; 

                //  add the header row to the table
                if (gv.HeaderRow != null)
                {
                    DataFlow.PrepareControlForExport(gv.HeaderRow);
                    table.Rows.Add(gv.HeaderRow);
                }
                //  add each of the data rows to the table
                foreach (GridViewRow row in gv.Rows)
                {
                    DataFlow.PrepareControlForExport(row);
                    table.Rows.Add(row);
                }

                //  add the footer row to the table
                if (gv.FooterRow != null)
                {
                    DataFlow.PrepareControlForExport(gv.FooterRow);
                    table.Rows.Add(gv.FooterRow);
                }

                //  render the table into the htmlwriter
                table.RenderControl(htw);

                //  render the htmlwriter into the response
                HttpContext.Current.Response.Write(sw.ToString());
                HttpContext.Current.Response.End();
            }
        }
    }

    /// <summary>
    /// Replace any of the contained controls with literals
    /// </summary>
    /// <param name="control"></param>
    private static void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control current = control.Controls[i];
            if (current is LinkButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
            }
            else if (current is ImageButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
            }
            else if (current is HyperLink)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
            }
            else if (current is DropDownList)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
            }
            else if (current is CheckBox)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
            }

            if (current.HasControls())
            {
                DataFlow.PrepareControlForExport(current);
            }
        }
    }
}
